package com.hmall.order.interceptor;

import com.hmall.util.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取表示登录后的表示
        String userId = request.getHeader("authorization");
        log.info("用户登录标识：{}" , userId);
        //如果没有就说明没有登录直接访问
        if(userId==null){
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);  //403禁止访问的状态码
            return false;
        }
        //如果有就表示登录过，保存id
        ThreadLocalUtils.setUserId(Long.parseLong(userId));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //移除用户登录的表示
        ThreadLocalUtils.removeUserId();
    }
}
